import { AuthUser } from '@/types/auth';

const TOKEN_KEY = 'auth_token';
const USER_KEY = 'auth_user';

/**
 * Token 管理
 */
export const tokenManager = {
  // 保存 token 到 localStorage
  setToken: (token: string): void => {
    if (typeof window !== 'undefined') {
      localStorage.setItem(TOKEN_KEY, token);
    }
  },

  // 从 localStorage 获取 token
  getToken: (): string | null => {
    if (typeof window !== 'undefined') {
      return localStorage.getItem(TOKEN_KEY);
    }
    return null;
  },

  // 删除 token
  removeToken: (): void => {
    if (typeof window !== 'undefined') {
      localStorage.removeItem(TOKEN_KEY);
    }
  },

  // 检查 token 是否存在
  hasToken: (): boolean => {
    return !!tokenManager.getToken();
  },
};

/**
 * 用户信息管理
 */
export const userManager = {
  // 保存用户信息到 localStorage
  setUser: (user: AuthUser): void => {
    if (typeof window !== 'undefined') {
      localStorage.setItem(USER_KEY, JSON.stringify(user));
    }
  },

  // 从 localStorage 获取用户信息
  getUser: (): AuthUser | null => {
    if (typeof window !== 'undefined') {
      const userStr = localStorage.getItem(USER_KEY);
      if (userStr) {
        try {
          return JSON.parse(userStr);
        } catch (error) {
          console.error('解析用户信息失败:', error);
          return null;
        }
      }
    }
    return null;
  },

  // 删除用户信息
  removeUser: (): void => {
    if (typeof window !== 'undefined') {
      localStorage.removeItem(USER_KEY);
    }
  },
};

/**
 * 生成简单的 JWT token（仅用于演示）
 */
export const generateToken = (user: AuthUser): string => {
  const header = btoa(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
  const payload = btoa(JSON.stringify({
    sub: user.id,
    username: user.username,
    role: user.role,
    iat: Math.floor(Date.now() / 1000),
    exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60), // 24小时后过期
  }));
  const signature = btoa('demo_signature'); // 实际项目中应该使用真实的签名

  return `${header}.${payload}.${signature}`;
};

/**
 * 验证 token 是否有效（简单验证）
 */
export const validateToken = (token: string): boolean => {
  if (!token) return false;

  try {
    const parts = token.split('.');
    if (parts.length !== 3) return false;

    const payload = JSON.parse(atob(parts[1]));
    const currentTime = Math.floor(Date.now() / 1000);

    // 检查是否过期
    if (payload.exp && payload.exp < currentTime) {
      return false;
    }

    return true;
  } catch (error) {
    console.error('Token 验证失败:', error);
    return false;
  }
};

/**
 * 从 token 中解析用户信息
 */
export const parseTokenUser = (token: string): Partial<AuthUser> | null => {
  try {
    const parts = token.split('.');
    if (parts.length !== 3) return null;

    const payload = JSON.parse(atob(parts[1]));
    return {
      id: payload.sub,
      username: payload.username,
      role: payload.role,
    };
  } catch (error) {
    console.error('解析 token 失败:', error);
    return null;
  }
};

/**
 * 清除所有认证信息
 */
export const clearAuth = (): void => {
  tokenManager.removeToken();
  userManager.removeUser();
};

/**
 * 检查用户是否有指定权限
 */
export const hasPermission = (user: AuthUser | null, permission: string): boolean => {
  if (!user) return false;
  return user.permissions.includes(permission) || user.role === 'admin';
};

/**
 * 检查用户是否有指定角色
 */
export const hasRole = (user: AuthUser | null, roles: string[]): boolean => {
  if (!user) return false;
  return roles.includes(user.role);
};

/**
 * 添加 Authorization header 到请求
 */
export const addAuthHeader = (headers: Record<string, string> = {}): Record<string, string> => {
  const token = tokenManager.getToken();
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  return headers;
}; 